package cn.chilemou;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author LiXingShuai
 * @className RabbitProducer
 * @description: TODO
 * @date 2023年04月10日
 * @version: 1.0
 */
public class RabbitProducer {

    private static final String EXCHANGE_NAME ="exchange_demo";
    private static final String ROUTING_KEY ="routingKey_demo";
    private static final String QUEUE_MAME ="queue_demo";

    private static final String IP_ADDRESS ="47.94.171.202";

    private static final int PORT = 5672;

    private static final String USERNAME = "likoukou";
    private static final String PWD = "likoukou";

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(IP_ADDRESS);
        connectionFactory.setPort(PORT);
        connectionFactory.setUsername(USERNAME);
        connectionFactory.setPassword(PWD);
        connectionFactory.setVirtualHost("host1");
        //connectionFactory.setUri("amqp://"+USERNAME+":"+PWD+"@"+IP_ADDRESS+":"+PORT+"/"+"host1");

        Connection connection = connectionFactory.newConnection();// 创建链接
        Channel channel = connection.createChannel();// 创建信道
        // 创建一个type=direct、持久化的、非自动删除的交换器
        channel.exchangeDeclare(EXCHANGE_NAME,"direct",true,false,null);
        channel.exchangeDeclarePassive(EXCHANGE_NAME);// 检查交换器是否已经存在（如果不存在则404 no exchange）
        //channel.exchangeBind("目标队列名","源队列名","routingKey");
        // 创建一个持久化、非排他的、非自动删除的队列
        channel.queueDeclare(QUEUE_MAME,true,false,false,null);
        // 将交换器与队列通过路由键绑定
        channel.queueBind(QUEUE_MAME,EXCHANGE_NAME,ROUTING_KEY);
        // 发送一条持久化的消息
        String message = "Hello world!";
        //channel.basicPublish(EXCHANGE_NAME,ROUTING_KEY, MessageProperties.PERSISTENT_TEXT_PLAIN,message.getBytes());
        for (int i = 0; i < 10; i++) {
            channel.basicPublish(EXCHANGE_NAME,ROUTING_KEY,new AMQP.BasicProperties().builder()
                    .contentType("text/plain")
                    .deliveryMode(2)
                    .priority(1)
                    .build(),message.getBytes());
        }
        TimeUnit.SECONDS.sleep(1);
        // 关闭资源
        channel.close();
        connection.close();
    }

}
